import sys
import pygame
from bullet import Bullet
from model.alien import Alien


def check_events(setting, screen, ship, bullets):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_event(event, setting, screen, ship, bullets)
        elif event.type == pygame.KEYUP:
            check_keyup_event(event, ship)


def check_keydown_event(event, setting, screen, ship, bullets):
    if event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_UP:
        ship.moving_up = True
    elif event.key == pygame.K_DOWN:
        ship.moving_down = True
    elif event.key == pygame.K_SPACE:
        new_bullet = Bullet(screen, setting, ship)
        bullets.add(new_bullet)
    elif event.key == pygame.K_q:
        sys.exit()


def check_keyup_event(event, ship):
    # 可能同时按住左右箭头
    if event.key == pygame.K_LEFT:
        ship.moving_left = False
    elif event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_UP:
        ship.moving_up = False
    elif event.key == pygame.K_DOWN:
        ship.moving_down = False


def update_screen(sw_swtting, screen, ship, bullets, aliens, background, ship_g, game_stats):
    screen.fill(sw_swtting.bg_color)
    screen.blit(background, (0, 0))
    # 显示玩家飞船
    ship.show_and_update()
    # 外星飞船移动
    move_alien(aliens)
    aliens.draw(screen)
    # 显示并更新子弹
    for bullet in bullets.sprites():
        bullet.show_and_update()
    # 检测子弹飞船碰撞
    pygame.sprite.groupcollide(bullets, aliens, True, True)
    # 检测玩家飞船和外星人碰撞
    pygame.sprite.groupcollide(ship_g, aliens, True, True)
    if len(aliens) <= 0 or len(ship_g) <= 0:
        # 打完了 or 玩家死亡 game over
        game_stats.game_active = False

    # 刷新屏幕
    pygame.display.flip()


def get_number_alien_x(sw_setting, alien_width):
    available_space_x = sw_setting.screen_width - 2 * alien_width
    number_alien_x = int(available_space_x / (2 * alien_width))
    return number_alien_x


def create_alien(sw_setting, screen, aliens, alien_number):
    alien = Alien(sw_setting, screen)
    alien_width = alien.rect.width
    alien.x = alien_width + 2 * alien_width * alien_number
    alien.rect.x = alien.x
    aliens.add(alien)


def create_alien_fleet(sw_setting, screen, aliens):
    alien = Alien(sw_setting, screen)
    number_alien_x = get_number_alien_x(sw_setting, alien.rect.width)

    for alien_number in range(number_alien_x):
        create_alien(sw_setting, screen, aliens, alien_number)


def move_alien(aliens):
    for alien in aliens:
        alien.move()
